//
//  FengAppExtensionHelper.m
//  FengSiriDemo
//
//  Created by Feng on 2021/7/27.
//

#define Feng_Siri_Data_Key @"siri_data_bkgubjxy"
#import "FengAppExtensionHelper.h"

@implementation FengAppExtensionHelper

#pragma mark -------------主工程使用
#pragma mark --获取groupId
+ (NSString *)getAppGroupId {
    NSString *bundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    return [NSString stringWithFormat:@"group.%@", bundleId];
}
#pragma mark --缓存数据
+ (void)cacheSiriData:(NSDictionary *)siriData {
    NSUserDefaults *userDefault = [[NSUserDefaults alloc] initWithSuiteName:[self getAppGroupId]];
    [userDefault setObject:siriData?:@{} forKey:Feng_Siri_Data_Key];
}

#pragma mark --获取缓存数据
+ (NSDictionary *)getCacheData {
    return [self getDataWithAppGroupId:[self getAppGroupId]];
}

#pragma mark --清楚缓存数据
+ (void)clearSiriData {
    NSUserDefaults *userDefault = [[NSUserDefaults alloc] initWithSuiteName:[self getAppGroupId]];
    [userDefault setObject:nil forKey:Feng_Siri_Data_Key];
}

#pragma mark -------------Extension工程使用
#pragma mark --获取groupId
+ (NSString *)getSiriAppGroupId {
    NSString *bundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSArray *subStrings = [bundleId componentsSeparatedByString:@"."];
    NSString *appGroupId = @"group";
    for (int i=0; i<subStrings.count-1; i++) { //去掉.后的最后一部分
        appGroupId = [NSString stringWithFormat:@"%@.%@",appGroupId, subStrings[i]];
    }
    return appGroupId;
}

#pragma mark --更新缓存数据
+ (void)updateSiriData:(NSDictionary *)siriData {
    NSUserDefaults *userDefault = [[NSUserDefaults alloc] initWithSuiteName:[self getSiriAppGroupId]];
    [userDefault setObject:siriData forKey:Feng_Siri_Data_Key];
}

#pragma mark --获取缓存数据
+ (NSDictionary *)getSiriData {
    return [self getDataWithAppGroupId:[self getSiriAppGroupId]];
}

#pragma mark ------------------------------------------内部函数
+ (NSDictionary *)getDataWithAppGroupId:(NSString *)appGroupId {
    NSUserDefaults *userDefault = [[NSUserDefaults alloc] initWithSuiteName:appGroupId];
    NSDictionary *data = [userDefault objectForKey:Feng_Siri_Data_Key];
    return data;
}

@end
